<!-- 新增 -->
<template>
  <div class="add">
    <div class="pageHeader">
      <i class="el-icon-arrow-left" @click="goBack"></i>
      <span v-if="id != undefined">编辑商户</span>
      <span v-else>添加商户</span>
    </div>
    <!-- 商户基本详情 -->
    <div class="column-form">
      <div class="title">商户基本详情</div>
      <myForm :formConfig="formConfig1" :formData="form" :labelWidth="labelWidth" :formInline="formInline"
        ref="addForm1">
        <!-- 经营地区 -->
        <template slot="area">
          <el-select v-model="form.province" placeholder="请选择所在省份" size="mini">
            <el-option label="超市/零售" value="1"></el-option>
            <el-option label="奶茶/美食" value="2"></el-option>
            <el-option label="美容/美发" value="3"></el-option>
            <el-option label="其他类别" value="100"></el-option>
          </el-select>
          <el-select v-model="form.city" placeholder="请选择所在市" size="mini" style="margin:0 10px;">
            <el-option label="超市/零售" value="1"></el-option>
            <el-option label="奶茶/美食" value="2"></el-option>
            <el-option label="美容/美发" value="3"></el-option>
            <el-option label="其他类别" value="100"></el-option>
          </el-select>
          <el-select v-model="form.county" placeholder="请选择所在省区/县" size="mini">
            <el-option label="超市/零售" value="1"></el-option>
            <el-option label="奶茶/美食" value="2"></el-option>
            <el-option label="美容/美发" value="3"></el-option>
            <el-option label="其他类别" value="100"></el-option>
          </el-select>
        </template>

        <!-- 地图位置 -->
        <template slot="lng">
          <el-button type="primary" @click="selectPosition">选择定位</el-button>
        </template>

        <!-- 门店logo -->
        <template slot="logoImage">
          <el-upload class="avatar-uploader" :http-request="(file) => { return fileUpload(file, 1) }"
            :before-upload="beforeUpload" action>
            <div v-if="form.logoImage" class="imgBox">
              <img :src="form.logoImage" class="avatar" />
            </div>

            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

        <!-- 门店介绍图 -->
        <template slot="descImage">
          <el-upload class="avatar-uploader" :http-request="(file) => { return fileUpload(file, 2) }"
            :before-upload="beforeUpload" action>
            <img v-for="(item, index) in form.descImageList" :key="index" :src="item" class="avatar" />
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>
      </myForm>
    </div>
    <!-- 商户认证信息 -->
    <div class="column-form">
      <div class="title">商户认证信息</div>
      <myForm :formConfig="formConfig2" :formData="form" :labelWidth="labelWidth" :formInline="formInline"
        ref="addForm2">
        <!-- 营业执照 -->
        <template slot="certNo1">
          <el-upload class="avatar-uploader" :http-request="(file) => { return fileUpload(file, 3) }"
            :before-upload="beforeUpload" action>
            <img v-if="form.certNo1" :src="form.certNo1" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

        <!-- 法人身份证照 -->
        <template slot="legalImage">
          <div class="idCard">
            <div>
              <el-upload class="avatar-uploader" :http-request="(file) => { return fileUpload(file, 4) }" action
                :before-upload="beforeUpload">
                <img v-if="form.legalFrontImage" :src="form.legalFrontImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <p>上传法人身份证人像面</p>
            </div>
            <div>
              <el-upload class="avatar-uploader" :http-request="(file) => { return fileUpload(file, 5) }" action
                :before-upload="beforeUpload">
                <img v-if="form.legalBackImage" :src="form.legalBackImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <p>上传法人身份证国徽像面</p>
            </div>
          </div>
        </template>
      </myForm>
    </div>
    <!-- 商户财务信息 -->
    <div class="column-form">
      <div class="title">商户财务信息</div>
      <myForm :formConfig="formConfig3" :formData="form" :labelWidth="labelWidth" :formInline="formInline"
        ref="addForm3">
      </myForm>
    </div>

    <div style="text-align: center;">
      <el-button type="primary" size="mini" @click="submit()" v-if="id != undefined">提交</el-button>
      <el-button type="primary" size="mini" @click="openPreview()">预览</el-button>
    </div>

    <!-- 选取定位 -->
    <ChoosePosition ref="ChoosePosition" @getLnglat="getLnglat" />
  </div>
</template>

<script>
import ChoosePosition from "./choosePosition.vue";
export default {
  components: { ChoosePosition },
  name: "Add",
  data() {
    // 营业执照号校验规则
    const validateLicenseNo = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入营业执照号"));
      }

      // 统一社会信用代码规则：18位，包含数字和大写字母
      const reg = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;

      if (!reg.test(value)) {
        return callback(new Error("请输入正确的营业执照号格式"));
      }

      // 校验码验证（根据国家标准GB/T 32100-2015）
      if (!checkLicenseCode(value)) {
        return callback(new Error("营业执照号校验不正确"));
      }

      callback();
    };
    // 校验码验证函数
    const checkLicenseCode = code => {
      // 加权因子
      const weightFactor = [
        1,
        3,
        9,
        27,
        19,
        26,
        16,
        17,
        20,
        29,
        25,
        13,
        8,
        24,
        10,
        30,
        28
      ];
      // 代码字符集
      const codeMap = new Map([
        ["0", 0],
        ["1", 1],
        ["2", 2],
        ["3", 3],
        ["4", 4],
        ["5", 5],
        ["6", 6],
        ["7", 7],
        ["8", 8],
        ["9", 9],
        ["A", 10],
        ["B", 11],
        ["C", 12],
        ["D", 13],
        ["E", 14],
        ["F", 15],
        ["G", 16],
        ["H", 17],
        ["J", 18],
        ["K", 19],
        ["L", 20],
        ["M", 21],
        ["N", 22],
        ["P", 23],
        ["Q", 24],
        ["R", 25],
        ["T", 26],
        ["U", 27],
        ["W", 28],
        ["X", 29],
        ["Y", 30]
      ]);

      // 分离校验码
      const codes = code.split("");
      const checkCode = codes.pop();

      // 计算前17位与对应因子乘积之和
      let sum = 0;
      for (let i = 0; i < 17; i++) {
        const codeValue = codeMap.get(codes[i]);
        if (codeValue === undefined) {
          return false; // 包含非法字符
        }
        sum += codeValue * weightFactor[i];
      }

      // 计算校验码
      const checkCodeValue = 31 - (sum % 31);
      const computedCheckCode = checkCodeValue === 31 ? 0 : checkCodeValue;

      // 查找对应的字符
      let actualCheckCode = "";
      for (const [key, value] of codeMap.entries()) {
        if (value === computedCheckCode) {
          actualCheckCode = key;
          break;
        }
      }

      return actualCheckCode === checkCode;
    };
    // 身份证号校验规则
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入身份证号"));
      }

      // 基本格式校验：18位，前17位为数字，最后一位可以是数字或X/x
      const reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!reg.test(value)) {
        return callback(new Error("请输入正确的18位身份证号格式"));
      }

      // 校验码验证
      if (!this.checkIdCardCode(value)) {
        return callback(new Error("身份证号校验不正确"));
      }

      // 校验出生日期
      if (!this.checkBirthday(value)) {
        return callback(new Error("身份证号中包含无效的出生日期"));
      }

      callback();
    };
    // 电话号码校验规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入电话号码"));
      }

      // 清除可能的空格
      const phone = value.replace(/\s/g, "");

      // 手机号校验规则（11位，以1开头，第二位3-9）
      const mobileReg = /^1[3-9]\d{9}$/;
      // 固定电话校验规则（带区号，可能有分机号）
      const landlineReg = /^0\d{2,3}-\d{7,8}(-\d{1,6})?$/;

      if (mobileReg.test(phone) || landlineReg.test(phone)) {
        callback();
      } else {
        return callback(
          new Error(
            "请输入正确的电话号码格式（手机号：11位数字；固定电话：区号-号码，如010-12345678）"
          )
        );
      }
    };
    // 数字校验规则
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入银行账号"));
      }

      // 纯数字校验正则
      const reg = /^\d+$/;

      if (!reg.test(value)) {
        return callback(new Error("只能输入数字"));
      }

      callback();
    };
    return {
      formInline: false,
      labelWidth: "100px",
      form: {},
      formConfig1: [
        {
          label: "商户名称",
          prop: "name",
          type: "input",
          placeholder: "请输入商户名称",
          rules: [
            { required: true, message: "请输入商户名称", trigger: "blur" }
          ]
        },
        {
          label: "行业类别",
          prop: "industryCategory",
          type: "select",
          options: [],
          rules: [
            { required: true, message: "请选择行业类别", trigger: "change" }
          ]
        },
        {
          label: "经营地区",
          slotName: "area",
          prop: "area",
          rules: [
            { required: true, message: "请选择经营地区", trigger: "change" }
          ]
        },
        {
          label: "详细地址",
          prop: "address",
          type: "input",
          placeholder: "请输入详细地址",
          rules: [
            { required: true, message: "请输入详细地址", trigger: "blur" }
          ]
        },
        {
          label: "地图位置",
          slotName: "lng",
          prop: "lng",
          rules: [
            { required: true, message: "请选择地图位置", trigger: "change" }
          ]
        },
        {
          label: "门店logo",
          slotName: "logoImage",
          prop: "logoImage",
          rules: [
            { required: true, message: "请上传门店logo", trigger: "change" }
          ]
        },
        {
          label: "营业时间",
          prop: "time",
          type: "timePickerRange",
          rules: [
            { required: true, message: "请选择营业时间", trigger: "change" }
          ]
        },
        { label: "门店介绍图", slotName: "descImage" },
        {
          label: "简介/特色",
          prop: "description",
          type: "textarea",
          placeholder: "",
          maxlength: 140
        }
      ],
      formConfig2: [
        {
          label: "营业执照号",
          prop: "licenceCode",
          type: "input",
          placeholder: "请输入营业执照号",
          rules: [
            { required: true, validator: validateLicenseNo, trigger: "blur" }
          ]
        },
        {
          label: "营业执照",
          prop: "licenceImage",
          slotName: "licenceImage",
          rules: [
            { required: true, message: "请上传营业执照", trigger: "change" }
          ]
        },
        {
          label: "法人姓名",
          prop: "legalName",
          type: "input",
          placeholder: "请输入法人姓名",
          rules: [
            { required: true, message: "请输入法人姓名", trigger: "blur" }
          ]
        },
        {
          label: "法人身份证号",
          prop: "legalNum",
          type: "input",
          placeholder: "请输入法人身份证号",
          rules: [
            { required: true, validator: validateIdCard, trigger: "blur" }
          ]
        },
        {
          label: "法人身份证照",
          prop: "legalImage",
          slotName: "legalImage",
          rules: [
            { required: true, message: "请上传法人身份证照", trigger: "change" }
          ]
        },
        {
          label: "联系人电话",
          prop: "legalTel",
          type: "input",
          placeholder: "请输入联系人电话",
          rules: [{ required: true, validator: validatePhone, trigger: "blur" }]
        }
      ],
      formConfig3: [
        {
          label: "开户银行名称",
          prop: "bankName",
          type: "input",
          placeholder: "请输入开户银行名称",
          rules: [
            { required: true, message: "请输入开户银行名称", trigger: "blur" }
          ]
        },
        {
          label: "开户支行名称",
          prop: "branchName",
          type: "input",
          placeholder: "请输入开户银行名称",
          rules: [
            { required: true, message: "请输入开户支行名称", trigger: "blur" }
          ]
        },
        {
          label: "结算账户类型",
          prop: "settlementType",
          type: "radio",
          radios: [
            { description: "对公账户", dataCode: 1 },
            { description: "个人账户", dataCode: 2 }
          ],
          rules: [
            {
              required: true,
              message: "请选择结算账户类型别",
              trigger: "change"
            }
          ]
        },
        {
          label: "银行账号",
          prop: "accountNum",
          type: "input",
          placeholder: "请输入银行账号",
          rules: [
            { required: true, validator: validateNumber, trigger: "blur" }
          ]
        },
        {
          label: "账号开户名",
          prop: "accountName",
          type: "input",
          placeholder: "请输入账号开户名",
          rules: [
            { required: true, message: "请输入账号开户名", trigger: "blur" }
          ]
        }
      ],
      id: this.$route.query.id
    };
  },
  created() {
    if (this.id) {
      // 查询详情
    }
  },
  methods: {
    // 返回
    goBack() {
      this.$router.push("/merchantManagement");
    },
    // 选择定位
    selectPosition() {
      this.$refs.ChoosePosition.show();
    },
    // 获取定位
    getLnglat(data) {
      const { lng, lat } = data;
      this.form.lng = lng;
      this.form.lat = lat;
    },
    // 门店logo上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件！");
      }
      return isImage;
    },
    fileUpload(file, num) { },
    //预览
    openPreview() {
      if (
        this.$refs.addForm1.submitValidate() &&
        this.$refs.addForm2.submitValidate() &&
        this.$refs.addForm3.submitValidate()
      ) {
        this.$emit("setActvie", "Preview");
      }
    },
    // 提交
    submit() { }
  }
};
</script>

<style scoped lang="scss">
.add {
  .pageHeader {
    font-size: 18px;
    font-weight: 550;
    margin-bottom: 10px;

    i {
      margin-right: 10px;
      cursor: pointer;
    }
  }

  .column-form {
    background: #f8f9fb;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 24px;

    ::v-deep .el-input__inner {
      max-width: 500px;
    }

    ::v-deep .el-textarea__inner {
      max-width: 700px;
      height: 100px;
    }

    ::v-deep .avatar-uploader-icon {
      background: #fff;
      width: 150px;
      height: 150px;
      line-height: 150px !important;
    }

    .avatar-uploader {
      img {
        width: 150px;
        margin: 0 auto;
      }
    }

    .idCard {
      display: flex;

      >div {
        margin-right: 50px;

        p {
          text-align: center;
          font-size: 12px;
          color: #027db4;
        }
      }
    }
  }

  .imgBox {
    width: 150px;
  }

  .preview-cls {
    display: flex;
    flex-direction: column;
    cursor: pointer;
    margin: 24px auto;
    width: 120px;
    padding: 10px 20px;
    color: #fff;
    font-weight: 16px;
    font-weight: 500;
    text-align: center;
    border-radius: 8px;
    background-color: blue;
  }
}
</style>